package com.haojin.java1;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author .29.
 * @create 2022-03-31 12:53
 */

//解决线程安全问题的方式三：Lock锁 --- JDK5.0新增
    /*
    面试题：synchronized 与 lock 的异同？
       相同：二者都可以解决线程安全问题
       不同：synchronized机制在执行完相应同步代码以后，自动释放同步监视器
            lock需要手动启动同步：lock()  还需要手动结束同步：unlock()

     */




    class Window implements Runnable{
//      1.创建ReentrantLock的对象
        private ReentrantLock lock = new ReentrantLock(true);

        private int ticket = 100;
    @Override
    public void run() {
        while(true){
            try{
                //2.调用lock()
                lock.lock();
                if(ticket > 0){

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }


                    System.out.println(Thread.currentThread().getName() +"*"+ticket);
                    ticket--;
                }else break;
            }finally{
                //3.调用解锁方法unlock()
                lock.unlock();
            }


        }

    }
}

public class LockTest {
    public static void main(String[] args) {
        Window a = new Window();
        Thread a1 = new Thread(a);
        Thread a2 = new Thread(a);
        Thread a3 = new Thread(a);

        a1.setName("窗口一:");
        a2.setName("窗口二:");
        a3.setName("窗口三:");

        a1.start();
        a3.start();
        a2.start();
    }
}
